<template>
  <a-cascader
    allow-clear
    placeholder="请选择行业"
    v-model:value="id"
    :show-search="{ filter: handleCascaderSearch }"
    :options="industryData.tree"
    @change="emit('change', $event)"
  />
</template>

<script lang="ts" setup>
import type { ShowSearchType } from 'ant-design-vue/lib/vc-cascader'
import { getIndustryTree } from '@/services/order/getIndustryList'
import type { Industry } from '@/core/interfaces/industry'
import { computed } from 'vue'

interface Props {
  industryList: Industry[]
  industryId: Industry['id'] | undefined
}

interface Emits {
  (e: 'update:industryId', s: Props['industryId']): void
  (e: 'change', s: any): void
}

defineOptions({
  name: 'IndustryCascader'
})

const emit = defineEmits<Emits>()

const props = withDefaults(defineProps<Props>(), {
  industryList: () => []
})

const industryData = computed(() => {
  // console.log(props.industryList, '这里的类型应该是什么格式的？')
  return getIndustryTree(props.industryList)
})

const id = computed({
  get() {
    const result = []
    if (props.industryId) {
      result.unshift(props.industryId)
      let parent = Object.values(industryData.value.diagram).find((v) => v.id === props.industryId)?.parent
      while (parent) {
        result.unshift(parent.id)
        parent = parent?.parent
      }
    }
    return result
  },
  set(value) {
    if (value && value.length) {
      emit('update:industryId', [...value].pop())
    } else {
      emit('update:industryId', undefined)
    }
  }
})

const handleCascaderSearch: ShowSearchType['filter'] = (inputValue, path) => {
  return path.some((option) => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1)
}
</script>
